//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - SaaS Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.IdentityModel.Policy;
using System.IdentityModel.Claims;
using System.IdentityModel.Tokens;

namespace Shp.Security.BrokeredReceiver
{
    /// <summary>
    /// This class will check access to the executing action against the authorized claims.
    /// </summary>
    public class ActionAuthorizationManager : ServiceAuthorizationManager
    {
        /// <summary>
        /// Checks authorization for the given operation context.
        /// </summary>
        /// <param name="operationContext">The <see cref="T:System.ServiceModel.OperationContext"></see>.</param>
        /// <returns>
        /// true if access is granted; otherwise, false. The default is true.
        /// </returns>
        public override bool CheckAccess(OperationContext operationContext)
        {
            // Extract the AuthorizationContext from the ServiceSecurityContext
            AuthorizationContext authContext = operationContext.ServiceSecurityContext.AuthorizationContext;

            // If there are no Claims in the AuthorizationContext, return false (Access Denied)
            // The issued token used to authenticate should contain claims 
            if (authContext.ClaimSets == null ||
                authContext.ClaimSets.Count == 0)
            {
                return false;
            }

            ClaimSet claimSet = FederationUtilities.GetX509CertificateClaimSet(authContext.ClaimSets);

            if (claimSet == null ||
                !FederationUtilities.IsTrustedIssuer(claimSet.Issuer))
            {
                return false;
            }

            IEnumerable<Claim> nameClaims = claimSet.FindClaims(ClaimTypes.Name, Rights.PossessProperty);
            foreach (Claim claim in nameClaims)
            {
                string name = claim.Resource as string;
                operationContext.IncomingMessageProperties.Add(ClaimTypes.Name, name);
            }

            IEnumerable<Claim> tenantClaims = claimSet.FindClaims(Constants.Multitenancy.TenantId, Rights.PossessProperty);
            foreach (Claim claim in tenantClaims)
            {
                string tenantId = claim.Resource as string;
                operationContext.IncomingMessageProperties.Add(Constants.Multitenancy.TenantId, tenantId);
            }
            tenantClaims = claimSet.FindClaims(Constants.Multitenancy.TenantAlias, Rights.PossessProperty);
            foreach (Claim claim in tenantClaims)
            {
                string tenantAlias = claim.Resource as string;
                operationContext.IncomingMessageProperties.Add(Constants.Multitenancy.TenantAlias, tenantAlias);
            }

            // Guard denies exectuion if the action is not in the token as a claim
            string action = operationContext.IncomingMessageHeaders.Action;
            IEnumerable<Claim> authorizationDecisionClaims = claimSet.FindClaims(ClaimTypes.AuthorizationDecision, Rights.PossessProperty);
            if (authorizationDecisionClaims == null)
            {
                return false;
            }

            foreach (Claim claim in authorizationDecisionClaims)
            {
                string authzAction = claim.Resource as string;
                if (!string.IsNullOrEmpty(authzAction) &&
                    authzAction.Equals(action, StringComparison.InvariantCultureIgnoreCase))
                {
                    return true;
                }
            }

            // If no AuthorizationDecision claim had a resource value that matched the 
            // current action name, return false (Access Denied)
            return false;
        }
    }
}